import { useCallback } from "react"
import { useSearchParams } from "react-router-dom"

/**
 *
 * @description 在  useSearchAction 做了一点扩展, 支持传入 key
 */
export function useSearchActionWithKey() {
    const [searchParams, setSearchParams] = useSearchParams()

    const setAction = useCallback(
        (key: string, val: string) => {
            setSearchParams(
                (prev) => {
                    const newParams = new URLSearchParams(prev)
                    newParams.set(key, val)
                    return newParams
                },
                { replace: true },
            )
        },
        [setSearchParams],
    )

    const clearAction = useCallback(
        (key: string) => {
            setSearchParams(
                (prev) => {
                    const newParams = new URLSearchParams(prev)
                    newParams.delete(key)
                    return newParams
                },
                { replace: true },
            )
        },
        [setSearchParams],
    )

    const getAction = useCallback(
        (key: string) => {
            return searchParams.get(key)
        },
        [searchParams],
    )

    const getActionList = useCallback(
        (keys: string[]) => {
            return keys.map((key) => getAction(key))
        },
        [getAction],
    )

    return {
        getAction,
        getActionList,
        setAction,
        clearAction,
    }
}
